import { createSlice } from "@reduxjs/toolkit";
import * as api from "request/api";
import { setToken as _setToken, getToken,removeToken } from "utils/token";

const appStore = createSlice({
  name: "appStore",
  initialState: {
    token: getToken() || "",
    // account: "", //用户信息
    account: JSON.parse(localStorage.getItem("userInfo")) || "",//用户信息
  },
  reducers: {
    setToken: (state, action) => {
      // 设置token
      state.token = action.payload;
      _setToken(action.payload);
    },
    setUserInfo: (state, action) => {
      // 设置用户信息
      state.account = action.payload;
      localStorage.setItem("userInfo", JSON.stringify(action.payload));
    },
    logOut: (state) => {
      // 退出登录
      state.token = "";
      state.account = "";
      removeToken();
    }
  },
});
const { setToken, setUserInfo,logOut } = appStore.actions;
// 获取用户信息
const fetchUserInfo = () => {
  return async (dispatch) => {
    // 异步操作
    const res = await api.userInfo();
    dispatch(setUserInfo(res.data));
  };
};
const loginOut = () => {
  return async (dispatch) => {
    // 异步操作
    const res = await api.userLogout();
    dispatch(logOut());
  };

}
export { setToken, fetchUserInfo,loginOut };

export default appStore.reducer;
